package com.app.net;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;

import com.app.util.Utils_Log;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/* @author sinawear
 * 540126629@qq.com
 */
public abstract class NetHelper_File {

	static final String TAG = "NetHelper_File";

	Handler handler = new Handler() ;

	Context mContext;
	DownloadManager mDM;
	long mDownloadId;
	Cursor mCursor;

	// 需要的两个参数
	String url = "";
	Map<String, Object> map = new HashMap<String, Object>();
	Params mParams = new Params();


	DownloadsChangeObserver mDownloadObserver = new DownloadsChangeObserver(handler);




	// 提供参数
	public class Params {
		public String TipTitle = "";
		public String TipDescription = "";

	};

	public abstract String init(Map<String,Object> datamap, Params params);
	public abstract void OnSuccess( File file);
	public abstract void OnFailure(String statusCode, String content, Throwable error);
	public abstract void OnFinal(String str);

	public NetHelper_File(Context context) {
		this.mContext = context;
		mDM = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

	}

	public void start() {

		url = init(map, mParams);
		if (url.length() == 0)
			return;


		Utils_Log.e(TAG, "url: "+url);

		Set<Map.Entry<String, Object>> data = map.entrySet();
		for(Map.Entry<String, Object> item : data){

			item.getKey();
			item.getValue();

		}

		/*
		 * mTipTitle = params.TipDescription; mTipDescription =
		 * params.TipDescription;
		 */

		/*
		 * String strNetRespone = download( ); Message msg = new Message();
		 * msg.obj = strNetRespone; handler.sendMessage(msg);
		 */
		download();

	}

	public void stop() {

		mDM.remove(mDownloadId);
		if(mCursor!=null){
			mCursor.unregisterContentObserver(mDownloadObserver);
			mCursor = null;
		}



	}

	private void download() {
		Request request = new Request(Uri.parse(url));

		 // 修改下载名称
		 int pos = url.lastIndexOf("/");
		 String FileName = url.substring(pos+1);

		 
//		 request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | request.NETWORK_WIFI);
		request.setAllowedOverRoaming(true)
				// 缺省是true
				.setTitle(mParams.TipTitle)
				// 用于信息查看
				.setDescription(mParams.TipDescription)
				// 用于信息查看
				.setDestinationInExternalPublicDir(
						Environment.DIRECTORY_DOWNLOADS, FileName)
				.setVisibleInDownloadsUi(false);

		mDownloadId = mDM.enqueue(request); // 加入下载队列

		// 监听下载进度
		mCursor = mDM.query(new DownloadManager.Query().setFilterById(mDownloadId));
		mCursor.registerContentObserver(mDownloadObserver);
		

	}

	// --
	private class DownloadsChangeObserver extends ContentObserver {


		/**
		 * Creates a content observer.
		 *
		 * @param handler The handler to run {@link #onChange} on, or null if none.
		 */
		public DownloadsChangeObserver(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			// 查询需要监听的字段
			// 比如要监听实时下载进度，查看当前下载状态：是否已经断开，或者下载失败等等

			//Log.d(TAG, "下载状态：" );

			Cursor c = mDM.query(new DownloadManager.Query().setFilterById(mDownloadId));
			int mSizeColunmId = c
					.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);

			if (c.moveToFirst()) {

				int bytesWritten = c.getInt(mSizeColunmId);
				int totalSize = c
						.getInt(c
								.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

				// if(bytesWritten != totalSize )
				{
					float progress = (float)bytesWritten/totalSize;
					OnProgress(bytesWritten, totalSize, progress);
				}

				if (bytesWritten == totalSize) { // 下载成功

					final File file = new File(getDownloadFileName(mDownloadId));

					OnSuccess(file);

					stop();

					OnFinal("");
				}

			}// endif

			c.close();



		}

	}

	private String getDownloadFileName(long download_id) {
		Uri videoUrl = mDM.getUriForDownloadedFile(download_id);

		DownloadManager.Query query = new DownloadManager.Query();
		Cursor cursor = mDM.query(query.setFilterById(download_id));
		int index = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
		int status = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);

		{
			// String[] column_names = cursor.getColumnNames();
			// System.out.println(column_names);
		}

		cursor.moveToFirst();
		int row_count = cursor.getCount();
		String file_name = cursor.getString(index);

		return file_name;

	}

	public void OnProgress(int bytesWritten, int totalSize, float percentage) {
		Utils_Log.e(TAG, "OnProgress: "+ ((float)bytesWritten/totalSize)*100.0f+"%" + "   percentage: "+percentage);

	}




	// ---------------------
	// 另种方案使用广播
	public BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			DownloadManager dm =
					(DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
			String action = intent.getAction();
			if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

				/*
				long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,
						0);
				// 查询
				DownloadManager.Query query = new DownloadManager.Query();
				query.setFilterById(downloadId);
				Cursor c = dm.query(query);
				if (c.moveToFirst()) {
					int columnIndex = c
							.getColumnIndex(DownloadManager.COLUMN_STATUS);
					if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

						String uriString = c.getString(c
								.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

						//removeDownload(downloadId); //
						//Toast.makeText(CopyOf_43MainActivity.this, // "get file complete: " +
						//		  uriString, 0).show(); // Uri.parse(uriString);
						int statusCode = 200;
						File file = new File(getDownloadFileName(downloadId));
						onSuccess(statusCode, file);

					}
				}// endif
				*/

			}// endif

		}// onReceive };// end class receiver
	};

}
